package com.wteam.dragon.system.util;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;

import java.lang.reflect.Field;

/**
 * MybatisPlus工具类
 * @Author 陈晓辉
 * @Date 2020/11/26 8:11
 */
public class WrapperUtil {
    /**
     * 模糊查询
     */
    public static <Children extends AbstractWrapper<T, String, Children>, T, R> void like(Children wrapper, R object){
        try {
            Field[] fields = ClassUtil.getDeclaredFields(object.getClass());
            for (Field field : fields){
                field.setAccessible(true);
                if(field.get(object) != null){
                    wrapper.like(StrUtil.toUnderlineCase(field.getName()), field.get(object));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 精确查询
     */
    public static <Children extends AbstractWrapper<T, String, Children>, T, R> void eq(Children wrapper, R object){
        try {
            Field[] fields = ClassUtil.getDeclaredFields(object.getClass());
            for (Field field : fields){
                field.setAccessible(true);
                if(field.get(object) != null){
                    wrapper.eq(StrUtil.toUnderlineCase(field.getName()), field.get(object));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 排序
     * @param order 0 倒叙 1顺序
     */
    public static <Children extends AbstractWrapper<T, String, Children>, T, R> void orderBy(Children wrapper, R object, Boolean order){
        try {
            Field[] fields = ClassUtil.getDeclaredFields(object.getClass());
            for (Field field : fields){
                field.setAccessible(true);
                if(field.get(object) != null){
                    wrapper.orderBy(true, order, StrUtil.toUnderlineCase(field.getName()));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
